package com.htfyun.ft.fragment.engineer;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.htfyun.ft.R;
import com.htfyun.ft.fragment.BaseFragment;
import com.htfyun.hardware.KeyEventController;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


/**
 * Created by sst on 2018/7/11.
 */

public class FragmentKey extends BaseFragment implements KeyEvent.Callback, View.OnClickListener {

    private final static String TAG = "FragmentKey";

    private KeyEventController keyEventController = KeyEventController.getInstance();

    private GridView gridView;
    private KeyAdapter keyAdapter;

    private TextView txtKeyCode;

    private List<KeyEventController.RK_KEY> keyDownList = new ArrayList<>();


    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_engineer_keys;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {

        txtKeyCode = (TextView) findViewById(R.id.txtKeyCode);
        gridView = (GridView) findViewById(R.id.gridView);

        keyAdapter = new KeyAdapter(getContext(), -1, KeyEventController.RK_KEY.values());

        gridView.setAdapter(keyAdapter);

        initBtn(R.id.btnStartRecovery);
        initBtn(R.id.btnStartRecoveryDialog);

    }

    private void initBtn(int resId) {
        View view = findViewById(resId);
        if (view != null) {
            view.setOnClickListener(this);
        }
    }

    @Override
    protected void onVisible() {
        super.onVisible();

        keyDownList.clear();

        keyEventController.registerKeyEventListener(this, null);

    }

    @Override
    protected void onInvisible() {
        super.onInvisible();

        keyEventController.unregisterKeyEventListener(this);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        KeyEventController.RK_KEY attr = keyEventController.getRKKeyByKeyCode(keyCode);

        if (attr == null) {
            return false;
        }

        String text = txtKeyCode.getText().toString();
        if (!TextUtils.isEmpty(text)) {
            text += "\n";

            String[] all = text.split("\n");
            if (all.length > 5) {
                text = "";
            }
        }
        String status = getString(R.string.test_key_current_keycode_status_down);
        String name = attr.getKeyLabel();
        text += getString(R.string.test_key_current_keycode, keyCode, status, name);
        txtKeyCode.setText(text);

        keyDownList.add(attr);
        keyAdapter.notifyDataSetChanged();

        return true;
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        return false;
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        Log.e(TAG, "onKeyUp keycode = " + keyCode);

        KeyEventController.RK_KEY attr = keyEventController.getRKKeyByKeyCode(keyCode);
        if (attr == null) {
            return false;
        }

        String text = txtKeyCode.getText().toString();
        if (!TextUtils.isEmpty(text)) {
            text += "\n";

            String[] all = text.split("\n");
            if (all.length > 5) {
                text = "";
            }
        }
        String status = getString(R.string.test_key_current_keycode_status_up);
        String name = attr.getKeyLabel();
        text += getString(R.string.test_key_current_keycode, keyCode, status, name);
        txtKeyCode.setText(text);

        keyDownList.remove(attr);
        keyAdapter.notifyDataSetChanged();

        return true;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStartRecovery:
                keyEventController.startRecovery();
                break;
            case R.id.btnStartRecoveryDialog:
                keyEventController.startRecoveryDialog();
                break;

        }

        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {

            }
        });
    }


    private final class KeyAdapter extends ArrayAdapter<KeyEventController.RK_KEY> {


        public KeyAdapter(@NonNull Context context, int resource, @NonNull KeyEventController.RK_KEY[] objects) {
            super(context, resource, objects);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView != null) {
                holder = (ViewHolder) convertView.getTag();
            } else {
                holder = new ViewHolder();
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_keys, null);
                holder.txt = (TextView) convertView.findViewById(R.id.txtKeys);

                convertView.setTag(holder);
            }

            KeyEventController.RK_KEY attr = getItem(position);
            if (attr != null) {
                if (!keyDownList.contains(attr)) {

                    holder.txt.setBackgroundColor(Color.YELLOW);

                } else {

                    holder.txt.setBackgroundColor(Color.GRAY);

                }


                String keyInfo = attr.getKeyLabel();
                keyInfo += getString(R.string.arrow) + attr.getKeyCode();

                holder.txt.setText(keyInfo);
            }
            return convertView;
        }
    }

    private final class ViewHolder {
        TextView txt;
    }




}
